package com.example.chapter12;


import java.util.Optional;

/*
*12.2.3.Optional类型
* */
public class Demo03 {

    Optional<String> optional = Optional.of("non-null value");


    Optional<String> optionalNullable = Optional.ofNullable(null);

    Optional<String> emptyOptional = Optional.empty();


    public static void main(String[] args) {
        Optional<String> optional = Optional.ofNullable("Hello, Optional!");

        if (optional.isPresent()) {
            System.out.println(optional.get());
        } else {
            System.out.println("Value is not present");
        }

        String valueOrDefault = optional.orElse("Default Value");
        System.out.println(valueOrDefault);

        try {
            String valueOrThrow = optional.orElseThrow(() -> new RuntimeException("No value present"));
            System.out.println(valueOrThrow);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        optional.ifPresent(System.out::println);

        Optional<String> mappedOptional = optional.map(String::toUpperCase);
        System.out.println(mappedOptional.orElse("Not Mapped"));

        Optional<String> filteredOptional = optional.filter(s -> s.contains("Optional"));
        System.out.println(filteredOptional.isPresent());
    }

}
